package com.xunyun.kotlinwc.main.adapter


import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.xunyun.kotlinwc.R
import com.xunyun.kotlinwc.databinding.ItemArticleBinding
import com.xunyun.kotlinwc.main.model.Article

/**
 * @author gl
 * @date 2021/9/10
 * @desc
 */
class ArticlePageAdapter(diffCallback: DiffUtil.ItemCallback<Article>) :
    PagedListAdapter<Article, ArticlePageAdapter.ArticleViewHolder>(diffCallback) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {

        val binding: ItemArticleBinding = DataBindingUtil.inflate(
            LayoutInflater.from(parent.context),
            R.layout.item_article, parent, false
        )

        return ArticleViewHolder(binding);
    }

    override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {

        getItem(position)?.run {
            holder.binding.tvTitle.text = title
            getCategory(holder.binding.tvCategory, this)
            holder.binding.tvTime.text = niceDate
            holder.binding.tvAuthor.text = getAuthor(this)
        }
    }

    class ArticleViewHolder(var binding: ItemArticleBinding) : RecyclerView.ViewHolder(binding.root)


    private fun getCategory(view: TextView, article: Article) {
        val value = if (article.superChapterName.isNullOrEmpty()) {
            if (article.chapterName.isNullOrEmpty()) {
                view.visibility = View.GONE
                ""
            } else {
                article.chapterName
            }
        } else {
            if (article.chapterName.isNullOrEmpty()) {
                article.superChapterName
            } else {
                article.superChapterName + "/${article.chapterName}"
            }
        }
        view.text = value
    }

    private fun getAuthor(article: Article): String? {
        if (article.author?.isEmpty()) {
            return article.shareUser
        }
        return article.author
    }


}